#pragma once

#include <iostream>

#include "httplib.h"
#include "common/request/add_contact_request.pb.h"
#include "common/responce/add_contact_responce.pb.h"
#include "common/request/find_one_request.pb.h"
#include "common/responce/find_one_responce.pb.h"
#include "common/request/del_contact_request.pb.h"
#include "common/responce/del_contact_responce.pb.h"
#include "dao/contact_mapper.hpp"
#include "common/responce/find_all_responce.pb.h"

using std::cout;
using std::cin;
using std::endl;
using namespace add_contact_req;
using namespace add_contact_res;


namespace web_contacts
{
    class ContactServer
    {
    public:
        //添加联系人
        //因为lambda表达式传值捕获的是不能修改的，为const，所以函数要加个const
        void addContact(const AddContactRequest&req, AddContactResponce *resp) const
        {
            try
            {
                //调用mapper方法添加联系人
                std::string uuid = mapper_.insertContact(req);
                //返回结果
                resp->set_uid(uuid);
                base_resp::BaseResponce *br = resp->mutable_base_resp();
                br->set_success(true);
            }
            catch(ContactException &e)
            {
                throw e;//抛到上层捕获
            }
        }

        //删除联系人
        void delContact(const del_contact_req::DelContactRequest &req, del_contact_resp::DelContactResponce *resp) const
        {
            try
            {
                std::string uuid = req.uuid();
                mapper_.delContact(uuid, resp);
                resp->mutable_base_resp()->set_success(true);
            }
            catch(ContactException &e)
            {
                throw e;
            }
        }
        //查找指定联系人
        void findOne(const find_one_req::FindOneRequest &req, find_one_res::FindOneRespone *resp) const 
        {
            try
            {
                //调用mapper接口查找联系人
                std::string uuid = mapper_.findOne(req.name());
                //返回结果
                resp->set_uuid(uuid);
                base_resp::BaseResponce *br = resp->mutable_base_resp();
                br->set_success(true);
            }
            catch(ContactException &e)
            {
                throw e;//抛到上层捕获
            }
        }
        //展示所有联系人
        void findAll(find_all_resp::FindAllResponce *resp) const
        {
            try
            {
                mapper_.findAll(resp);
                base_resp::BaseResponce *br = resp->mutable_base_resp();
                br->set_success(true);
            }
            catch(const ContactException &e)
            {
                throw e;
            }
        }
    private:
        ContactsMapper mapper_;
    };
}